// src/stores/auth.ts
import { defineStore } from 'pinia'
import { reactive } from 'vue'
import type { User } from '@/api/User'
import apiClient from '@/api/axios'
import router from '@/router'

interface AuthState {
  user: User | null
  token: string | null
}

export const useAuthStore = defineStore('auth', () => {
  const state = reactive<AuthState>({
    user: JSON.parse(localStorage.getItem('user') || 'null'),
    token: localStorage.getItem('token')
  })

  const getLoginUserInfo = async (token: string): Promise<User | null> => {
    try {
      const response = await apiClient.get('/user/getLoginUser', {
        headers: { token }
      })
      console.log('拉取到用户信息:', response.data.data)
      return response.data.data
    } catch (error) {
      console.error('获取用户信息失败', error)
      return null
    }
  }

  const login = async (userAccount: string, userPassword: string): Promise<void> => {
    try {
      const response = await apiClient.post('/user/login', {
        userAccount,
        userPassword
      })
      console.log("从后端读取出来的数据为:" + JSON.stringify(response))
      if (response.data.code === 0) {
        const authToken = response.data.data
        console.log('登录成功，接收到token值:', authToken)
        const userInfo = await getLoginUserInfo(authToken)
        if (userInfo) {
          state.token = authToken
          state.user = userInfo
          console.log("auth服务提供的user对象:" + JSON.stringify(state.user))
          localStorage.setItem('user', JSON.stringify(userInfo))
          localStorage.setItem('token', authToken)
          alert("登录成功")
          router.push("/")
        }
      } else {
        alert(response.data.message)
      }
    } catch (error) {
      alert(error.message)
    }
  }

  const logout = (): void => {
    state.user = null
    state.token = null
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    router.push('/login')
  }

  const checkLogin = (): boolean => {
    const storedUser = localStorage.getItem('user')
    const storedToken = localStorage.getItem('token')
    if (storedUser && storedToken) {
      state.user = JSON.parse(storedUser)
      state.token = storedToken
      console.log("检查登录状态:state.user=" + JSON.stringify(state.user) + ",state.token = " + state.token)
      return true
    }

    return false
  }

  const getLoginUser = (): User | null => {
    if (checkLogin()) {
      return state.user
    } else {
      router.push('/user/login')
      return null
    }
  }

  const getAuthToken = (): string | null => {
    if (checkLogin()) {
      return state.token
    } else {
      router.push('/user/login')
      return null
    }
  }

  return {
    state,
    login,
    logout,
    checkLogin,
    getLoginUser,
    getAuthToken
  }
})

/**
 * <template>
 *   <div>
 *     <h1>用户资料</h1>
 *     <div v-if="authStore.state.user">
 *       <p>用户ID: {{ authStore.state.user.id }}</p>
 *       <p>用户名: {{ authStore.state.user.userName }}</p>
 *       <button @click="authStore.logout">退出登录</button>
 *     </div>
 *   </div>
 * </template>
 *
 * <script setup lang="ts">
 * import { useAuthStore } from '@/stores/auth'
 *
 * const authStore = useAuthStore()
 *
 * authStore.checkLogin() // 初始化时检查登录状态
 * </script>
 */